package com.jicheng.service.impl;

import com.jicheng.Utils.DESEncryptUtil;
import com.jicheng.constants.Constants;
import com.jicheng.dto.data.SyncInfoParams;
import com.jicheng.dto.data.integrity.DelIntegerParams;
import com.jicheng.dto.data.log.LogsInfo;
import com.jicheng.dto.data.log.SyncDetailInfo;
import com.jicheng.dto.data.log.SyncLogsInfo;
import com.jicheng.dto.data.profile.*;
import com.jicheng.dto.data.task.DelParams;
import com.jicheng.dto.data.task.TaskInfo;
import com.jicheng.dto.data.task.Template;
import com.jicheng.dto.data.task.template.*;
import com.jicheng.dto.data.task.template.item.*;
import com.jicheng.dto.data.task.template.item.Box.Column;
import com.jicheng.dto.task.DelattachParams;
import com.jicheng.dto.task.SynTemplLibParams;
import com.jicheng.dto.task.TemplateParams;
import com.jicheng.entity.*;
import com.jicheng.entity.task.Attachment;
import com.jicheng.entity.task.template.TemplateMap;
import com.jicheng.entity.task.template.item.*;
import com.jicheng.ext.dto.UploadLocalFileParams;
import com.jicheng.ext.enums.ApiResponseCode;
import com.jicheng.ext.exceptions.BaseException;
import com.jicheng.ext.util.*;
import com.jicheng.mapper.*;
import com.jicheng.mapper.template.*;
import com.jicheng.service.IDataSyncService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.sql.SQLIntegrityConstraintViolationException;
import java.util.Date;
import java.util.List;

import com.jicheng.Utils.FileUtils;

@Service
public class DataSyncServiceImpl implements IDataSyncService {
    private Logger log = LoggerFactory.getLogger(DataSyncServiceImpl.class);


    @Autowired
    private CadreInformationMapper cadreInformationMapper;
    @Autowired
    private BusinessSituationMapper businessSituationMapper;
    @Autowired
    private FamilyMainMemberMapper familyMainMemberMapper;
    @Autowired
    private FamilyForeignMapper familyForeignMapper;
    @Autowired
    private GiftTurnInMapper giftTurnInMapper;
    @Autowired
    private GoAbroadCertificatesMapper goAbroadCertificatesMapper;
    @Autowired
    private GoAbroadSituationMapper goAbroadSituationMapper;
    @Autowired
    private HonorSituationMapper honorSituationMapper;
    @Autowired
    private HouseSituationMapper houseSituationMapper;
    @Autowired
    private MaritalStatusMapper maritalStatusMapper;
    @Autowired
    private ResumeMapper resumeMapper;
    @Autowired
    private LogsMapper logsMapper;
    @Autowired
    private SituationMapper situationMapper;
    @Autowired
    private ParttimeSituationMapper parttimeSituationMapper;
    @Autowired
    private SyncInfoMapper syncInfoMapper;
    @Autowired
    private LogsDetailMapper logsDetailMapper;
    @Autowired
    private AttachmentMapper attachmentMapper;

    @Autowired
    TemplateLibraryMapper templateLibraryMapper;

    @Transactional
    @Override
    public void syncProfileDetail(List<ProfileSyncInfo> params, String userId) {


        if (CollectionUtils.isEmpty(params)) {
            throw new BaseException(ApiResponseCode.参数为空);
        }
        if (params.size() > 10) {
            throw new BaseException(ApiResponseCode.不允许此操作, "同步数据过大");
        }
        notNull("userId", userId);
        String reportId;
        String appId;
        String cadreId;

        log.info("--------- 开始同步数据------------");
        for (ProfileSyncInfo profileSyncInfo : params) {
            reportId = profileSyncInfo.getReportId();
            appId = profileSyncInfo.getAppId();
            cadreId = profileSyncInfo.getCadreId();
            if (StringUtils.isEmpty(reportId)) {
                throw new BaseException(ApiResponseCode.参数为空, "填报id不能为空");
            }
            //干部基本信息
            CadreInformationInfo cadreInformationInfo = profileSyncInfo.getCadreInformationInfo();
            if (cadreInformationInfo != null) {
                CadreInformation copy = BeanConvertor.copy(cadreInformationInfo, CadreInformation.class);
                copy.setId(cadreId);
                copy.setReportId(reportId);
                copy.setUserId(userId);
                copy.setAppId(appId);
                copy.setCadreId(cadreId);
                int exist = cadreInformationMapper.isExist(cadreId);
                if (exist > 0) {
                    cadreInformationMapper.updateByPrimaryKeySelective(copy);
                } else {
                    cadreInformationMapper.insertSelective(copy);
                }
            }

            //配偶，子女经商办企业情况
            List<BusinessSituationInfo> businessSituationInfo = profileSyncInfo.getBusinessSituationInfo();
            if (CollectionUtils.isNotEmpty(businessSituationInfo)) {
                for (BusinessSituationInfo info : businessSituationInfo) {
                    BusinessSituation copy = BeanConvertor.copy(info, BusinessSituation.class);
//                    copy.setId(cadreId);
                    copy.setCadreId(cadreId);
                    copy.setReportId(reportId);
                    copy.setAppId(appId);
                    int exist = businessSituationMapper.isExist(copy.getId());
                    if (exist > 0) {
                        businessSituationMapper.updateByPrimaryKeySelective(copy);
                    } else {
                        businessSituationMapper.insertSelective(copy);
                    }
                }

            }
            //家庭成员在国（境）外定居（留学）情况
            /*List<FamilyForeignInfo> familyForeignInfo = profileSyncInfo.getFamilyForeignInfo();
            if (CollectionUtils.isNotEmpty(familyForeignInfo)) {
                for (FamilyForeignInfo info : familyForeignInfo) {
                    FamilyForeign copy = BeanConvertor.copy(info, FamilyForeign.class);
                    copy.preCreate();
                    if (StringUtils.isEmpty(copy.getId())) {
                        copy.setId(UUIDUtils.uuid());
                    }
                    copy.setReportId(reportId);
                    familyForeignEntityMapper.insertSelective(copy);
                }
            }*/
            //家庭成员以及社会关系
            List<FamilyMainMemberInfo> familyMainMemberInfo = profileSyncInfo.getFamilyMainMemberInfo();
            if (CollectionUtils.isNotEmpty(familyMainMemberInfo)) {
                for (FamilyMainMemberInfo info : familyMainMemberInfo) {
                    FamilyMainMember copy = BeanConvertor.copy(info, FamilyMainMember.class);
                    copy.setCadreId(cadreId);
                    copy.setReportId(reportId);
//                    copy.setId(cadreId);
                    copy.setAppId(appId);
                    int exist = familyMainMemberMapper.isExist(copy.getId());
                    if (exist > 0) {
                        familyMainMemberMapper.updateByPrimaryKeySelective(copy);
                    } else {
                        familyMainMemberMapper.insertSelective(copy);
                    }
                }
            }
            //礼金上交情况
            /*List<GiftTurnInInfo> giftTurnInInfo = profileSyncInfo.getGiftTurnInInfo();
            if (CollectionUtils.isNotEmpty(giftTurnInInfo)) {
                for (GiftTurnInInfo info : giftTurnInInfo) {
                    GiftTurnIn copy = BeanConvertor.copy(info, GiftTurnIn.class);
                    copy.preCreate();
                    if (StringUtils.isEmpty(copy.getId())) {
                        copy.setId(UUIDUtils.uuid());
                    }
                    copy.setReportId(reportId);
                    giftTurnInEntityMapper.insertSelective(copy);
                }
            }*/
            //出国证件情况
            /*List<GoAbroadCertificatesInfo> goAbroadCertificatesInfo = profileSyncInfo.getGoAbroadCertificatesInfo();
            if (CollectionUtils.isNotEmpty(goAbroadCertificatesInfo)) {
                for (GoAbroadCertificatesInfo info : goAbroadCertificatesInfo) {
                    GoAbroadCertificates copy = BeanConvertor.copy(info, GoAbroadCertificates.class);
                    copy.preCreate();
                    if (StringUtils.isEmpty(copy.getId())) {
                        copy.setId(UUIDUtils.uuid());
                    }
                    copy.setReportId(reportId);
                    goAbroadCertificatesEntityMapper.insertSelective(copy);
                }
            }*/
            //出国情况
            /*List<GoAbroadSituationInfo> goAbroadSituationInfo = profileSyncInfo.getGoAbroadSituationInfo();
            if (CollectionUtils.isNotEmpty(goAbroadSituationInfo)) {
                for (GoAbroadSituationInfo info : goAbroadSituationInfo) {
                    GoAbroadSituation copy = BeanConvertor.copy(info, GoAbroadSituation.class);
                    copy.preCreate();
                    if (StringUtils.isEmpty(copy.getId())) {
                        copy.setId(UUIDUtils.uuid());
                    }
                    copy.setReportId(reportId);
                    goAbroadSituationEntityMapper.insertSelective(copy);
                }
            }*/
            //荣誉情况
            /*List<HonorSituationInfo> honorSituationInfo = profileSyncInfo.getHonorSituationInfo();
            if (CollectionUtils.isNotEmpty(honorSituationInfo)) {
                for (HonorSituationInfo info : honorSituationInfo) {
                    HonorSituation copy = BeanConvertor.copy(info, HonorSituation.class);
                    copy.preCreate();
                    if (StringUtils.isEmpty(copy.getId())) {
                        copy.setId(UUIDUtils.uuid());
                    }
                    copy.setReportId(reportId);
                    honorSituationEntityMapper.insertSelective(copy);
                }

            }*/
            //房产情况
            List<HouseSituationInfo> houseSituationInfo = profileSyncInfo.getHouseSituationInfo();
            if (CollectionUtils.isNotEmpty(houseSituationInfo)) {
                for (HouseSituationInfo info : houseSituationInfo) {
                    HouseSituation copy = BeanConvertor.copy(info, HouseSituation.class);
//                    copy.setId(cadreId);
                    copy.setCadreId(cadreId);
                    copy.setReportId(reportId);
                    copy.setAppId(appId);
                    int exist = houseSituationMapper.isExist(copy.getId());
                    if (exist > 0) {
                        houseSituationMapper.updateByPrimaryKeySelective(copy);
                    } else {
                        houseSituationMapper.insertSelective(copy);
                    }
                }
            }
            //婚姻情况
            /*List<MaritalStatusInfo> maritalStatusInfo = profileSyncInfo.getMaritalStatusInfo();
            if (CollectionUtils.isNotEmpty(maritalStatusInfo)) {
                for (MaritalStatusInfo info : maritalStatusInfo) {
                    MaritalStatus copy = BeanConvertor.copy(info, MaritalStatus.class);
                    copy.preCreate();
                    if (StringUtils.isEmpty(copy.getId())) {
                        copy.setId(UUIDUtils.uuid());
                    }
                    copy.setReportId(reportId);
                    maritalStatusEntityMapper.insertSelective(copy);
                }
            }*/
            //个人履历
            /*List<ResumeInfo> resumeInfo = profileSyncInfo.getResumeInfo();
            if (CollectionUtils.isNotEmpty(resumeInfo)) {
                for (ResumeInfo info : resumeInfo) {
                    Resume copy = BeanConvertor.copy(info, Resume.class);
                    copy.preCreate();
                    if (StringUtils.isEmpty(copy.getId())) {
                        copy.setId(UUIDUtils.uuid());
                    }
                    copy.setReportId(reportId);
                    resumeEntityMapper.insertSelective(copy);
                }
            }*/
            //兼职情况
            List<ParttimeSituationInfo> parttimeSituationInfos = profileSyncInfo.getParttimeSituationInfo();
            if (CollectionUtils.isNotEmpty(parttimeSituationInfos)) {
                for (ParttimeSituationInfo info : parttimeSituationInfos) {
                    ParttimeSituation copy = BeanConvertor.copy(info, ParttimeSituation.class);
//                    copy.setId(cadreId);
                    copy.setCadreId(cadreId);
                    copy.setReportId(reportId);
                    copy.setAppId(appId);
                    int exist = parttimeSituationMapper.isExist(copy.getId());
                    if (exist > 0) {
                        parttimeSituationMapper.updateByPrimaryKeySelective(copy);
                    } else {
                        parttimeSituationMapper.insertSelective(copy);
                    }

                }
            }
            //各种情况汇总到一张表
            SituationInfo situationInfo = profileSyncInfo.getSituationInfo();
            if (situationInfo != null) {
                Situation copy = BeanConvertor.copy(situationInfo, Situation.class);
                copy.setId(cadreId);
                copy.setCadreId(cadreId);
                copy.setReportId(reportId);
                copy.setAppId(appId);
                int exist = situationMapper.isExist(cadreId);
                if (exist > 0) {
                    situationMapper.updateByPrimaryKeySelective(copy);
                } else {
                    situationMapper.insertSelective(copy);
                }
            }

        }

    }

    @Override
    public String syncPhotos(MultipartFile file) {
        if (file == null) {
            throw new BaseException(ApiResponseCode.参数为空);
        }
        InputStream inputStream = null;
        try {
            inputStream = file.getInputStream();
        } catch (IOException e) {
            throw new BaseException(ApiResponseCode.数据异常, "获取文件异常");
        }
        //存到一个路径就好了
        String dir = Constants.FILE_PATH + "image/" + DateUtils.format(new Date(), "yyyyMMddHHmmss") + "/";
        File dest = new File(dir);
        String absolutePath = dest.getAbsolutePath()+"/";
//        FileManager fileManager = new FileManager();
//        UploadLocalFileParams uploadLocalFileParams = new UploadLocalFileParams();
//        uploadLocalFileParams.setFileName(file.getOriginalFilename());
//        uploadLocalFileParams.setDir(dir);
//        fileManager.uploadLocal(inputStream, uploadLocalFileParams);
        //加密
        try {
            File toFile = FileUtils.multipartFileToFile(file);
            DESEncryptUtil.encryption("H:/key.k", toFile, "encrypt", absolutePath);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return absolutePath + file.getOriginalFilename();
//        return (dir + file.getOriginalFilename());
    }

    @Transactional
    @Override
    public void syncLogs(LogsInfo params) {
        int size = params.getSyncLogsInfos().size();

        if (size > 100) {
            throw new BaseException(ApiResponseCode.不允许此操作, "数据长度过长");
        }

        List<SyncLogsInfo> syncLogsInfos = params.getSyncLogsInfos();
        for (SyncLogsInfo syncLogsInfo : syncLogsInfos) {

            if (syncLogsInfo == null) {
                continue;
            }
//                notNull("userName", syncLogsInfo.getUserName());
            Logs copy = BeanConvertor.copy(syncLogsInfo, Logs.class);
            copy.preCreate();
            try{

                logsMapper.insertSelective(copy);
            }catch (Exception e){
                if (e.getMessage().contains("Duplicate entry")){
                    logsMapper.updateByPrimaryKeySelective(copy);
                }
            }
        }

        List<SyncDetailInfo> syncDetailInfos = params.getSyncDetailInfos();
        for (SyncDetailInfo syncDetailInfo : syncDetailInfos) {

            if (syncDetailInfo == null) {
                continue;
            }
//                notNull("id", syncDetailInfo.getId());
            LogDetail copy = BeanConvertor.copy(syncDetailInfo, LogDetail.class);
            if (StringUtils.isEmpty(copy.getId())) {
                copy.setId(UUIDUtils.uuid());
            }
            logsDetailMapper.insertSelective(copy);
        }

    }

    @Override
    public void saveSynInfo(SyncInfoParams syncInfoParams) {
        if (syncInfoParams != null) {
            AppDataHistory copy = BeanConvertor.copy(syncInfoParams, AppDataHistory.class);
            if (StringUtils.isEmpty(syncInfoParams.getId())) {
                copy.setId(UUIDUtils.uuid());
            }
            syncInfoMapper.insertSelective(copy);
        }
    }

    @Autowired
    ActiveInterviewMapper activeInterviewMapper;
    @Autowired
    TemplateMapMapper templateMapMapper;
    @Autowired
    FindProblemMapper findProblemMapper;
    @Autowired
    GrassrootsInvestigationMapper grassrootsInvestigationMapper;
    @Autowired
    LifeMeetingMapper lifeMeetingMapper;
    @Autowired
    SupervisionAndInspectionMapper supervisionAndInspectionMapper;

    @Autowired
    OpinionReviewMapper opinionReviewMapper;
    @Autowired
    TalkAndRemindMapper talkAndRemindMapper;
    @Autowired
    TaskMapper taskMapper;
    @Autowired
    CustomFormMapper customFormMapper;
    @Autowired
    TaskAttachmentMapper taskAttachmentMapper;

    @Transactional
    @Override
    public void syncTaskDetail(List<TaskInfo> params) {

        if (CollectionUtils.isEmpty(params)) {
            throw new BaseException(ApiResponseCode.参数为空);
        }
        if (params.size() > 10) {
            throw new BaseException(ApiResponseCode.不允许此操作, "同步数据过大");
        }

        for (TaskInfo taskInfo : params) {
            String taskId = taskInfo.getTaskId();
            String appId = taskInfo.getAppId();
            String appUser = taskInfo.getAppUser();
            Task task = BeanConvertor.copy(taskInfo, Task.class);
            task.setId(taskInfo.getTaskId());
            int existTask = taskMapper.isExist(taskId);
            if (existTask <= 0) {
                taskMapper.insertSelective(task);
            } else {
                taskMapper.updateByPrimaryKeySelective(task);
            }
            //同步附件
            List<String> attachments = taskInfo.getAttachments();
            for (String attachmentId : attachments) {
                TaskAttachment taskTemplate = new TaskAttachment();
                taskTemplate.setTaskId(taskId);
                taskTemplate.setAttachmentId(attachmentId);
                int exist = taskAttachmentMapper.isExist(taskId, attachmentId);
                if (exist <= 0) {
                    taskAttachmentMapper.insertSelective(taskTemplate);
                }
            }

            //同步模板
            List<Template> templateBeans = taskInfo.getTemplateBeans();
            for (Template templateBean : templateBeans) {
                ActiveInterviewBean activeInterviewBean = templateBean.getActiveInterviewBean();
                if (activeInterviewBean != null) {
                    String templateId = activeInterviewBean.getId();//模板id
                    TemplateMap templateMap = BeanConvertor.copy(activeInterviewBean, TemplateMap.class);
                    templateMap.setId(templateId);
                    templateMap.setTaskId(taskId);
                    templateMap.setCreateTime(activeInterviewBean.getCreateTime());
                    templateMap.setName(activeInterviewBean.getName());
                    templateMap.setAttribute('1');
                    templateMap.setType(Constants.TYPE_TALK);
                    templateMap.setImgPath(activeInterviewBean.getImgPath());
                    templateMap.setAppId(appId);
                    templateMap.setAppUser(appUser);
                    int existTemplate = templateMapMapper.isExist(templateId);
                    if (existTemplate <= 0) {
                        templateMapMapper.insertSelective(templateMap);
                    } else {
                        templateMapMapper.updateByPrimaryKeySelective(templateMap);
                    }
                    List<ActiveInterviewItemBean> activeInterviewBeanBeans = activeInterviewBean.getBeans();
                    for (ActiveInterviewItemBean bean : activeInterviewBeanBeans) {
                        ActiveInterviewItem copy = BeanConvertor.copy(bean, ActiveInterviewItem.class);
                        int isExist = activeInterviewMapper.isExist(bean.getId());
                        if (isExist <= 0) {
                            copy.setId(bean.getId());
                            copy.setTaskId(taskId);
                            copy.setTemplateId(templateId);
                            activeInterviewMapper.insertSelective(copy);
                        } else {
                            activeInterviewMapper.updateByPrimaryKeySelective(copy);
                        }

                    }
                }

                FindProblemBean findProblemBean = templateBean.getFindProblemBean();
                if (findProblemBean != null) {
                    String templateId = findProblemBean.getId();
                    TemplateMap templateMap = BeanConvertor.copy(findProblemBean, TemplateMap.class);
                    templateMap.setId(templateId);
                    templateMap.setTaskId(taskId);
                    templateMap.setCreateTime(findProblemBean.getCreateTime());
                    templateMap.setName(findProblemBean.getName());
                    templateMap.setAttribute('1');
                    templateMap.setImgPath(findProblemBean.getImgPath());
                    templateMap.setAppId(appId);
                    templateMap.setAppUser(appUser);
                    templateMap.setType(Constants.TYPE_SUPERVISION);
                    int existTemplate = templateMapMapper.isExist(templateId);
                    if (existTemplate <= 0) {
                        templateMapMapper.insertSelective(templateMap);
                    } else {
                        templateMapMapper.updateByPrimaryKeySelective(templateMap);
                    }
                    List<FindProblemItemBean> findProblemBeanBeans = findProblemBean.getBeans();
                    for (FindProblemItemBean bean : findProblemBeanBeans) {
                        FindProblemItem copy = BeanConvertor.copy(bean, FindProblemItem.class);
                        int isExist = findProblemMapper.isExist(bean.getId());
                        if (isExist <= 0) {
                            copy.setId(bean.getId());
                            copy.setTaskId(taskId);
                            copy.setTemplateId(templateId);
                            findProblemMapper.insertSelective(copy);
                        } else {
                            findProblemMapper.updateByPrimaryKeySelective(copy);
                        }
                    }
                }
                GrassrootsInvestigationBean grassrootsInvestigationBean = templateBean.getGrassrootsInvestigationBean();
                if (grassrootsInvestigationBean != null) {
                    String templateId = grassrootsInvestigationBean.getId();
                    TemplateMap templateMap = BeanConvertor.copy(grassrootsInvestigationBean, TemplateMap.class);
                    templateMap.setId(templateId);
                    templateMap.setTaskId(taskId);
                    templateMap.setCreateTime(grassrootsInvestigationBean.getCreateTime());
                    templateMap.setName(grassrootsInvestigationBean.getName());
                    templateMap.setAttribute('1');
                    templateMap.setImgPath(grassrootsInvestigationBean.getImgPath());
                    templateMap.setAppId(appId);
                    templateMap.setAppUser(appUser);
                    templateMap.setType(Constants.TYPE_RESEARCH);
                    int existTemplate = templateMapMapper.isExist(templateId);
                    if (existTemplate <= 0) {
                        templateMapMapper.insertSelective(templateMap);
                    } else {
                        templateMapMapper.updateByPrimaryKeySelective(templateMap);
                    }
                    List<GrassrootsInvestigationItemBean> grassrootsInvestigationBeanBeans = grassrootsInvestigationBean.getBeans();
                    for (GrassrootsInvestigationItemBean bean : grassrootsInvestigationBeanBeans) {
                        GrassrootsInvestigationItem copy = BeanConvertor.copy(bean, GrassrootsInvestigationItem.class);
                        int isExist = grassrootsInvestigationMapper.isExist(bean.getId());
                        if (isExist <= 0) {
                            copy.setId(bean.getId());
                            copy.setTaskId(taskId);
                            copy.setTemplateId(templateId);
                            grassrootsInvestigationMapper.insertSelective(copy);
                        } else {
                            grassrootsInvestigationMapper.updateByPrimaryKeySelective(copy);
                        }
                    }
                }

                LifeMeetingBean lifeMeetingBean = templateBean.getLifeMeetingBean();
                if (lifeMeetingBean != null) {
                    String templateId = lifeMeetingBean.getId();
                    TemplateMap templateMap = BeanConvertor.copy(lifeMeetingBean, TemplateMap.class);
                    templateMap.setId(templateId);
                    templateMap.setTaskId(taskId);
                    templateMap.setCreateTime(lifeMeetingBean.getCreateTime());
                    templateMap.setName(lifeMeetingBean.getName());
                    templateMap.setAttribute('1');
                    templateMap.setImgPath(lifeMeetingBean.getImgPath());
                    templateMap.setAppId(appId);
                    templateMap.setAppUser(appUser);
                    templateMap.setType(Constants.TYPE_MEETING);
                    int existTemplate = templateMapMapper.isExist(templateId);
                    if (existTemplate <= 0) {
                        templateMapMapper.insertSelective(templateMap);
                    } else {
                        templateMapMapper.updateByPrimaryKeySelective(templateMap);
                    }
                    List<LifeMeetingItemBean> lifeMeetingItemBeans = lifeMeetingBean.getBeans();
                    for (LifeMeetingItemBean bean : lifeMeetingItemBeans) {
                        LifeMeetingItem copy = BeanConvertor.copy(bean, LifeMeetingItem.class);
                        int isExist = lifeMeetingMapper.isExist(bean.getId());
                        if (isExist <= 0) {
                            copy.setId(bean.getId());
                            copy.setTaskId(taskId);
                            copy.setTemplateId(templateId);
                            lifeMeetingMapper.insertSelective(copy);
                        } else {
                            lifeMeetingMapper.updateByPrimaryKeySelective(copy);
                        }
                    }
                }
                OpinionReviewBean opinionReviewBean = templateBean.getOpinionReviewBean();
                if (opinionReviewBean != null) {
                    String templateId = opinionReviewBean.getId();
                    TemplateMap templateMap = BeanConvertor.copy(opinionReviewBean, TemplateMap.class);
                    templateMap.setId(templateId);
                    templateMap.setTaskId(taskId);
                    templateMap.setCreateTime(opinionReviewBean.getCreateTime());
                    templateMap.setName(opinionReviewBean.getName());
                    templateMap.setAttribute('1');
                    templateMap.setImgPath(opinionReviewBean.getImgPath());
                    templateMap.setAppId(appId);
                    templateMap.setAppUser(appUser);
                    templateMap.setType(Constants.TYPE_OPINION);
                    int existTemplate = templateMapMapper.isExist(templateId);
                    if (existTemplate <= 0) {
                        templateMapMapper.insertSelective(templateMap);
                    } else {
                        templateMapMapper.updateByPrimaryKeySelective(templateMap);
                    }
                    OpinionReview opinionReview = BeanConvertor.copy(opinionReviewBean, OpinionReview.class);
                    int isExist = opinionReviewMapper.isExist(opinionReview.getId());
                    if (isExist <= 0) {
                        opinionReview.setId(opinionReview.getId());
                        opinionReview.setTaskId(taskId);
                        opinionReview.setTemplateId(templateId);
                        opinionReviewMapper.insertSelective(opinionReview);
                    } else {
                        opinionReviewMapper.updateByPrimaryKeySelective(opinionReview);
                    }
                }

                SupervisionAndInspectionBean supervisionAndInspectionBean = templateBean.getSupervisionAndInspectionBean();
                if (supervisionAndInspectionBean != null) {
                    String templateId = supervisionAndInspectionBean.getId();
                    TemplateMap templateMap = BeanConvertor.copy(supervisionAndInspectionBean, TemplateMap.class);
                    templateMap.setId(templateId);
                    templateMap.setTaskId(taskId);
                    templateMap.setCreateTime(supervisionAndInspectionBean.getCreateTime());
                    templateMap.setName(supervisionAndInspectionBean.getName());
                    templateMap.setAttribute('1');
                    templateMap.setImgPath(supervisionAndInspectionBean.getImgPath());
                    templateMap.setAppId(appId);
                    templateMap.setAppUser(appUser);
                    templateMap.setType(Constants.TYPE_SUPERVISION);
                    int existTemplate = templateMapMapper.isExist(templateId);
                    if (existTemplate <= 0) {
                        templateMapMapper.insertSelective(templateMap);
                    } else {
                        templateMapMapper.updateByPrimaryKeySelective(templateMap);
                    }
                    List<SupervisionAndInspectionItemBean> supervisionAndInspectionBeanBeans = supervisionAndInspectionBean.getBeans();
                    for (SupervisionAndInspectionItemBean bean : supervisionAndInspectionBeanBeans) {
                        SupervisionAndInspectionItem copy = BeanConvertor.copy(bean, SupervisionAndInspectionItem.class);
                        int isExist = supervisionAndInspectionMapper.isExist(bean.getId());
                        if (isExist <= 0) {
                            copy.setId(bean.getId());
                            copy.setTaskId(taskId);
                            copy.setTemplateId(templateId);
                            supervisionAndInspectionMapper.insertSelective(copy);
                        } else {
                            supervisionAndInspectionMapper.updateByPrimaryKeySelective(copy);
                        }
                    }
                }

                TalkAndRemindBean talkAndRemindBean = templateBean.getTalkAndRemindBean();
                if (talkAndRemindBean != null) {
                    String templateId = talkAndRemindBean.getId();
                    TemplateMap templateMap = BeanConvertor.copy(talkAndRemindBean, TemplateMap.class);
                    templateMap.setId(templateId);
                    templateMap.setTaskId(taskId);
                    templateMap.setCreateTime(talkAndRemindBean.getCreateTime());
                    templateMap.setName(talkAndRemindBean.getName());
                    templateMap.setAttribute('1');
                    templateMap.setImgPath(talkAndRemindBean.getImgPath());
                    templateMap.setAppId(appId);
                    templateMap.setAppUser(appUser);
                    templateMap.setType(Constants.TYPE_TALK);
                    int existTemplate = templateMapMapper.isExist(templateId);
                    if (existTemplate <= 0) {
                        templateMapMapper.insertSelective(templateMap);
                    } else {
                        templateMapMapper.updateByPrimaryKeySelective(templateMap);
                    }
                    TalkAndRemind talkAndRemind = BeanConvertor.copy(talkAndRemindBean, TalkAndRemind.class);
                    int isExist = talkAndRemindMapper.isExist(talkAndRemind.getId());
                    if (isExist <= 0) {
                        talkAndRemind.setId(talkAndRemindBean.getId());
                        talkAndRemind.setTaskId(taskId);
                        talkAndRemind.setTemplateId(templateId);
                        talkAndRemindMapper.insertSelective(talkAndRemind);
                    } else {
                        talkAndRemindMapper.updateByPrimaryKeySelective(talkAndRemind);
                    }
                }

                CustomFormBean customFormBean = templateBean.getCustomFormBean();
                if (customFormBean != null) {
                    String templateId = customFormBean.getId();
                    TemplateMap templateMap = BeanConvertor.copy(customFormBean, TemplateMap.class);
                    templateMap.setId(templateId);
                    templateMap.setTaskId(taskId);
                    templateMap.setCreateTime(customFormBean.getCreateTime());
                    templateMap.setName(customFormBean.getName());
                    templateMap.setAttribute('1');
                    templateMap.setRowNum(customFormBean.getRowNum());
                    templateMap.setImgPath(customFormBean.getImgPath());
                    templateMap.setAppId(appId);
                    templateMap.setAppUser(appUser);
                    int existTemplate = templateMapMapper.isExist(templateId);
                    if (existTemplate <= 0) {
                        templateMapMapper.insertSelective(templateMap);
                    } else {
                        templateMapMapper.updateByPrimaryKeySelective(templateMap);
                    }

                    List<CustomFormItemBean> customFormBeanBeans = customFormBean.getBeans();
                    for (CustomFormItemBean bean : customFormBeanBeans) {
                        List<Column> columns = bean.getColumn();
                        for (Column column : columns) {
                            CustomFormItem customFormItem = BeanConvertor.copy(column, CustomFormItem.class);
                            int isExist = customFormMapper.isExist(customFormItem.getId());
                            if (isExist <= 0) {
                                customFormItem.setTaskId(taskId);
                                customFormItem.setTemplateId(templateId);
                                customFormItem.setRowId(column.getId());
                                customFormMapper.insertSelective(customFormItem);
                            } else {
                                customFormMapper.updateByPrimaryKeySelective(customFormItem);
                            }
                        }
                    }
                }
            }
        }
    }

    @Override
    public void syncAttachment(MultipartFile file, String attachmentId) {

        //文件名空格处理
        String fileName = file.getOriginalFilename().replace(" ", "");
        if (file == null || StringUtils.isEmpty(attachmentId)) {
            throw new BaseException(ApiResponseCode.参数为空);
        }
        InputStream inputStream = null;
        try {
            inputStream = file.getInputStream();
        } catch (IOException e) {
            throw new BaseException(ApiResponseCode.数据异常, "获取文件异常");
        }
        //存到一个路径就好了
        String dir = "/usr/app/Downloads/attachment/" + DateUtils.format(new Date(), "yyyyMMddHHmmss") + "/";
        File dest = new File(dir);
        String absolutePath = dest.getAbsolutePath().replace("\\","/")+"/";
//        FileManager fileManager = new FileManager();
//        UploadLocalFileParams uploadLocalFileParams = new UploadLocalFileParams();
//        uploadLocalFileParams.setFileName(fileName);
//        uploadLocalFileParams.setDir(dir);
//        fileManager.uploadLocal(inputStream, uploadLocalFileParams);
//        //加密
        try {
            File toFile = FileUtils.multipartFileToFile(file);
            DESEncryptUtil.encryption("H:/key.k", toFile, "encrypt", absolutePath);
            //加密完成，删除未加密原文件
            FileUtils.delteTempFile(toFile);
        } catch (Exception e) {
            e.printStackTrace();
        }

        Attachment attachment = new Attachment();
        attachment.setId(attachmentId);
        attachment.setName(fileName);
        attachment.setSize(file.getSize());
        attachment.setPath(absolutePath + fileName);
        int isExist = attachmentMapper.isExist(attachmentId);
        if (isExist > 0) {
            attachmentMapper.updateByPrimaryKeySelective(attachment);
        } else {
            attachmentMapper.insertSelective(attachment);

        }
    }

    @Transactional
    @Override
    public void delTask(DelParams delParams) {
        List<String> taskId = delParams.getTaskId();
        if (taskId != null && !taskId.isEmpty()) {
            for (String id : taskId) {
                taskMapper.delTask(id);
                templateMapMapper.delTemplate("task_id", id);
                activeInterviewMapper.del("task_id", id);
                findProblemMapper.del("task_id", id);
                grassrootsInvestigationMapper.del("task_id", id);
                lifeMeetingMapper.del("task_id", id);
                opinionReviewMapper.del("task_id", id);
                supervisionAndInspectionMapper.del("task_id", id);
                talkAndRemindMapper.del("task_id", id);
                customFormMapper.del("task_id", id);
                taskAttachmentMapper.delAll("task_id", id);
            }
        }
        List<String> templateId = delParams.getTemplateId();
        if (templateId != null && !templateId.isEmpty()) {
            for (String id : templateId) {
                templateMapMapper.delTemplate("id", id);
                activeInterviewMapper.del("template_id", id);
                findProblemMapper.del("template_id", id);
                grassrootsInvestigationMapper.del("template_id", id);
                lifeMeetingMapper.del("template_id", id);
                opinionReviewMapper.del("template_id", id);
                supervisionAndInspectionMapper.del("template_id", id);
                talkAndRemindMapper.del("template_id", id);
                customFormMapper.del("template_id", id);
            }
        }
        List<String> activeInterview = delParams.getActiveInterview();
        if (activeInterview != null && !activeInterview.isEmpty()) {
            for (String id : activeInterview) {
                activeInterviewMapper.del("id", id);
            }
        }
        List<String> findProblem = delParams.getFindProblem();
        if (findProblem != null && !findProblem.isEmpty()) {
            for (String id : findProblem) {
                findProblemMapper.del("id", id);
            }
        }
        List<String> grassrootaInvestigation = delParams.getGrassrootaInvestigation();
        if (grassrootaInvestigation != null && !grassrootaInvestigation.isEmpty()) {
            for (String id : grassrootaInvestigation) {
                grassrootsInvestigationMapper.del("id", id);
            }
        }
        List<String> lifeMeeting = delParams.getLifeMeeting();
        if (lifeMeeting != null && !lifeMeeting.isEmpty()) {
            for (String id : lifeMeeting) {
                lifeMeetingMapper.del("id", id);
            }
        }
        List<String> opinionReview = delParams.getOpinionReview();
        if (opinionReview != null && !opinionReview.isEmpty()) {
            for (String id : opinionReview) {
                opinionReviewMapper.del("id", id);
            }
        }
        List<String> supervisionAndInspection = delParams.getSupervisionAndInspection();
        if (supervisionAndInspection != null && !supervisionAndInspection.isEmpty()) {
            for (String id : supervisionAndInspection) {
                supervisionAndInspectionMapper.del("id", id);
            }
        }

        List<String> talkAndRemind = delParams.getTalkAndRemind();
        if (talkAndRemind != null && !talkAndRemind.isEmpty()) {
            for (String id : talkAndRemind) {
                talkAndRemindMapper.del("id", id);
            }
        }
        List<String> custom = delParams.getCustom();
        if (custom != null && !custom.isEmpty()) {
            for (String id : custom) {
                customFormMapper.del("row_id", id);
            }
        }
        //删除资料库文件
        List<String> attachment = delParams.getAttachment();
        if (attachment != null && !attachment.isEmpty()) {
            for (String id : attachment) {
                attachmentMapper.del("id", id);
            }

        }

        //删除任务附件
        List<DelattachParams> taskAttachment = delParams.getTaskAttachment();
        for (DelattachParams del : taskAttachment) {
            taskAttachmentMapper.del(del.getTaskId(), del.getAttachmentId());
        }
    }

    @Override
    public int checkAttachment(String attachmentId) {
        int isExist = attachmentMapper.checkAttachment(attachmentId);
        return isExist;
    }

    @Override
    public void saveAttachmented(String[] attachmentId, String taskId) {
        for (String id : attachmentId) {
            Attachment attachment = new Attachment();
            attachment.setId(id);
            attachment = attachmentMapper.selectByPrimaryKey(attachment);
            attachment.setTaskId(taskId);
            attachmentMapper.insertSelective(attachment);

        }
    }

    @Transactional
    @Override
    public void delIntegrity(DelIntegerParams delIntegerParams) {
        List<String> businessSituationInfo = delIntegerParams.getBusinessSituationInfo();
        for (String id : businessSituationInfo) {

            businessSituationMapper.del(id);
        }
        List<String> familyMainMemberInfo = delIntegerParams.getFamilyMainMemberInfo();
        for (String id : familyMainMemberInfo) {

            familyMainMemberMapper.del(id);
        }
        List<String> houseSituationInfo = delIntegerParams.getHouseSituationInfo();
        for (String id : houseSituationInfo) {

            houseSituationMapper.del(id);
        }
        List<String> parttimeSituationInfo = delIntegerParams.getParttimeSituationInfo();
        for (String id : parttimeSituationInfo) {

            parttimeSituationMapper.del(id);
        }
    }

    @Transactional
    @Override
    public void syncTemplate(SynTemplLibParams params) {
        if (params.getTemplateParams() != null) {
            for (TemplateParams param : params.getTemplateParams()) {
                TemplateLibrary copy = BeanConvertor.copy(param, TemplateLibrary.class);
                int isExist = templateLibraryMapper.isExist(copy.getId());
                if (isExist > 0) {
                    templateLibraryMapper.updateByPrimaryKeySelective(copy);
                } else {

                    templateLibraryMapper.insertSelective(copy);
                }
            }
        }
        //删除模板路中的模板
        if (params.getDelId().size() > 0) {
            for (String id : params.getDelId()) {
                templateLibraryMapper.delTemplLib(id);
            }
        }
    }


}
